/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2009, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: pcd_to_pointcloud.cpp 33238 2010-03-11 00:46:58Z rusu $
 *
 */

/**

\author Radu Bogdan Rusu

@b pcd_to_pointcloud is a simple node that loads PCD (Point Cloud Data) files from disk and publishes them as ROS messages on the network.

 **/

// ROS core
#include <ros/ros.h>
#include <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <sensor_msgs/Image.h>
#include "pcl_ros/publisher.h"
#include <sys/stat.h>

using namespace std;

class ImageGenerator
{
  protected:
    string tf_frame_;
    ros::NodeHandle nh_;
    ros::NodeHandle private_nh_;
    pcl::PointCloud < pcl::PointXYZRGB > cloud;
    pcl::PCDReader reader;
  
    
  public:

    // ROS messages
    sensor_msgs::Image image;

    string file_name_, cloud_topic_;
    long int index_;
    double rate_;

    ros::Publisher pub_;
        


  int fexist( string fname ) 
  {
    struct stat buffer ;
    if ( stat( fname.c_str(), &buffer )==-1 ) return 1 ;
    return 0 ;
  }
    
    
    
    ////////////////////////////////////////////////////////////////////////////////
    ImageGenerator () 
    {
      
      index_ = 0;
      // Maximum number of outgoing messages to be queued for delivery to subscribers = 1

      cloud_topic_ = "output";
      pub_ =  nh_.advertise <sensor_msgs::Image> (cloud_topic_.c_str (), 1);
     
      char fname[30];
      sprintf(fname, "%li", index_);
      file_name_ = fname;
      file_name_ += ".pcd";
    }

    ////////////////////////////////////////////////////////////////////////////////
    // Start
    int
      start ()
    {
      if (reader.read (file_name_, cloud))
        return (-1);
     else
      return (0);
    }

    ////////////////////////////////////////////////////////////////////////////////
    // Spin (!)
    bool spin ()
    {

      double interval = rate_ * 1e+6;
      bool lookMore = true;
      char fname[30];
      while (nh_.ok ())
      {
		
	try
	{
	  pcl::toROSMsg (cloud, image); //convert the cloud
	}
	  catch (std::runtime_error e)
	{
	  ROS_ERROR_STREAM("Error in converting cloud to image message: "
                            << e.what());
	  return 1; //fail!
	}
	
        if (pub_.getNumSubscribers () > 0)
        {
         
          pub_.publish (image);
        }
        else
        {
          ros::Duration (0.001).sleep ();
          continue;
        }

        usleep (interval);

        if (interval == 0)                      // We only publish once if a 0 seconds interval is given
          break;
	
	// Adding code to move to next pcd file. If no new file found, keep sending last file
	if(lookMore)
	{
	 index_++;
	       
	  sprintf(fname, "%li", index_);
	  file_name_ = fname;
	  file_name_ += ".pcd";
	
	// if (fexist(file_name_))
	// {
	   if(reader.read (file_name_, cloud)==0)
	   {
	   }
	 else
	   {
	     index_--;
	    lookMore = false;
	    return(1);
	    }
	  
	//}
	}

      }

      ros::Duration (3.0).sleep ();
      return (true);
    }


};

/* ---[ */
int
  main (int argc, char** argv)
{
  

  ros::init (argc, argv, "pcd2imagestream");

  ImageGenerator c;
  
  c.index_     = 0; // Starting index of the PCD file stream
  c.rate_      = atof (argv[1]);

  if (c.start () == -1)
  {
    ROS_ERROR ("Could not load files. Exiting.");
    return (-1);
  }
  c.spin ();

  return (0);
}
/* ]--- */
